<template>
  <el-button class="left-6 top-6 z-10" @click="$router.back()" type="text" size="large">
    <el-icon><Back /></el-icon> 返回
  </el-button>
  <el-card class="my-invite-panel question-detail-header mb-4 mt-10" shadow="never">
    <!-- <el-button class=" left-6 top-6 z-10" @click="$router.back()" type="text" size="large">
          <el-icon><Back /></el-icon> 返回
        </el-button> -->
    <div class="panel-title flex items-center justify-between mb-2">
      <!-- 左侧：头像、用户名、专业标签 -->
      <div class="flex items-center gap-2">
        <img
          v-if="question.avatar"
          :src="question.avatar"
          class="w-7 h-7 rounded-full object-cover border border-blue-100 shadow-sm cursor-pointer" />
        <span v-if="question.username" class="text-sm font-medium text-blue-700 cursor-pointer mr-2">
          {{ question.username }}
        </span>
        <el-tag
          v-for="(tag, index) in question.specialtyTagNames"
          :key="index"
          :type="tagTypes[index % tagTypes.length]"
          size="small"
          class="rounded-full tag-modern">
          {{ tag }}
        </el-tag>
        <span class="text-xs text-gray-500 ml-2">{{ formatTime(question.createTime) }}</span>
      </div>

      <!-- 右侧：状态标签和经典答疑标志 -->
      <div class="flex items-center gap-2">
        <!-- 问题状态标签 -->
        <el-tag
          v-if="question.status == 1 || question.status == 2 || question.status == 3"
          :type="getStatusTagType"
          size="small"
          class="rounded-full status-tag"
          effect="dark">
          {{ getStatusText }}
        </el-tag>

        <!-- 经典答疑标志 class="classic-qa-badge" -->
        <div v-if="tab == 'answer'" >
          <!-- <div class="badge-content">
            <div class="badge-icon">🏆</div>
            <div class="badge-text">
              <span class="badge-title">经典答疑</span>
              <span class="badge-subtitle">经典案例</span>
            </div>
          </div>
          <div class="badge-shine"></div> w-10 h-10-->
          <img :src="jd" class=" h-12" style="border-radius:65px;"/>
        </div>
      </div>
      <!-- 操作按钮组 - 只有作者且问题状态为正常时才显示 -->
      <div v-if="question.status === 0 && isQuestionAuthor" class="flex items-center gap-2 ml-auto">
        <el-button type="primary" round size="small" @click="showEditDialog = true" class="font-bold min-w-[80px]">
          编辑
        </el-button>
        <el-button type="warning" round size="small" @click="showCloseDialog = true" class="font-bold min-w-[80px]">
          关闭
        </el-button>
        <el-button type="danger" round size="small" @click="handleDelete" class="font-bold min-w-[80px]">
          删除
        </el-button>
      </div>
    </div>
    <div class="main-title text-xl font-bold mb-1 leading-snug text-blue-900">{{ question.title }}</div>
    <div class="desc text-base text-gray-700 mb-3 whitespace-pre-line" v-html="question.content"></div>

    <div class="flex flex-wrap items-center justify-between gap-3 mb-2">
      <div class="flex items-center gap-3">
        <el-button
          :type="isFollowed ? 'info' : 'primary'"
          round
          size="small"
          @click="handleToggleFollow"
          class="font-bold min-w-[80px]"
          >{{ isFollowed ? '已关注' : '关注问题' }}</el-button
        >
        <!-- <el-button type="primary" round size="small" @click="$emit('scrollToAnswerInput')" class="font-bold min-w-[80px]">写回答</el-button> -->
        <!-- <el-button type="success" round size="small" @click="$emit('showInviteDialog')" class="font-bold min-w-[80px]">邀请回答</el-button> -->
        <el-button type="default" round size="small" @click="$emit('showShare')" class="font-bold min-w-[80px]"
          >分享</el-button
        >
        <span class="text-gray-400 text-sm ml-2"
          >{{ question.viewCount }} 浏览 · {{ question.answerCount }} 回答 · {{ question.likeCount }} 关注</span
        >
        <el-dropdown trigger="click">
          <span class="action-btn">
            <el-icon><MoreFilled /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="showReportDialog = true">举报</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>

      <div class="flex items-center gap-2">
        <!-- 答疑相关按钮操作区域 -->
        <div v-if="tab == 'invite'">
          <el-button
            type="primary"
            round
            size="small"
            @click="startAudioMeeting"
            :loading="isStartingVoiceCall"
            :disabled="isStartingVoiceCall"
            class="font-bold min-w-[80px]">
            {{ isStartingVoiceCall ? '发起中...' : '音频答疑' }}
          </el-button>
          <el-button type="success" round size="small" @click="startVideoMeeting" class="font-bold min-w-[80px]">
            视频答疑
          </el-button>
          <el-button type="info" round size="small" @click="startTextChat" class="font-bold min-w-[80px]">
            文字答疑
          </el-button>
        </div>
        <el-button
          v-if="(question.status === 0 && isQuestionAuthor) || tab == 'invite'"
          type="warning"
          round
          size="small"
          @click="showQARecords"
          class="font-bold min-w-[80px]">
          答疑记录
        </el-button>
      </div>
    </div>
  </el-card>

  <!-- 编辑问题弹框 -->
  <QuestionDialog v-model:visible="showEditDialog" :question-id="question.id" @success="handleEditSuccess" />

  <!-- 关闭问题弹框 -->
  <el-dialog v-model="showCloseDialog" title="关闭问题" width="500px" :close-on-click-modal="false" append-to-body>
    <div class="close-form">
      <div class="form-item">
        <label class="form-label required">关闭原因</label>
        <el-input
          v-model="closeReason"
          type="textarea"
          :rows="4"
          placeholder="请输入关闭原因..."
          maxlength="200"
          show-word-limit />
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showCloseDialog = false">取消</el-button>
        <el-button type="warning" @click="confirmClose">确认关闭</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 使用举报组件 -->
  <ReportDialog v-model="showReportDialog" :report-info="reportInfo" @success="handleReportSuccess" />

  <!-- 文字聊天功能已移至全局App.vue处理 -->

  <!-- 语音通话弹窗 -->
  <VoiceCallDialog
    v-model:visible="showVoiceCall"
    :call-data="voiceCallData"
    :base-url="voiceCallBaseUrl"
    @call-end="handleVoiceCallEnd" />

  <!-- 答疑记录弹窗 -->
  <el-dialog v-model="showRecordDialog" title="答疑记录" width="700px" :close-on-click-modal="false">
    <el-tabs v-model="recordTab">
      <el-tab-pane label="音视频答疑" name="call">
        <div v-if="callRecordList.length">
          <div v-for="item in callRecordList" :key="item.id" class="record-row">
            <!-- 发起方 -->
            <div class="record-col left">
              <img :src="item.callerAvatar" class="avatar" />
              <div class="flex flex-col min-w-0">
                <span class="name">{{ item.callerName }}</span>
                <span class="role">发起方</span>
              </div>
            </div>
            <!-- 通话类型icon -->
            <div class="record-col center">
              <el-icon class="icon text-blue-500" v-if="item.callType === 1"><Phone /></el-icon>
              <el-icon class="icon text-blue-500" v-else><VideoCamera /></el-icon>
              <span class="time">{{ item.startTime }}</span>
            </div>
            <!-- 接收方 -->
            <div class="record-col right">
              <div class="flex flex-col min-w-0 items-end">
                <span class="name">{{ item.calleeName }}</span>
                <span class="role">接收方</span>
              </div>
              <img :src="item.calleeAvatar" class="avatar" />
            </div>
          </div>
        </div>
        <div v-else class="text-center text-slate-400 py-8">暂无音视频答疑记录</div>
      </el-tab-pane>
      <el-tab-pane label="文字答疑" name="chat">
        <div v-if="chatRecordList.length">
          <div v-for="item in chatRecordList" :key="item.id" class="record-row">
            <!-- 发起方 -->
            <div class="record-col left">
              <img :src="item.senderAvatar || '/src/assets/avatar.png'" class="avatar" />
              <div class="flex flex-col min-w-0">
                <span class="name">{{ item.senderName }}</span>
                <span class="role">发起方</span>
              </div>
            </div>
            <!-- 文本icon -->
            <div class="record-col center">
              <el-icon class="icon text-blue-500"><Message /></el-icon>
              <span class="text-blue-500 cursor-pointer" @click="handleItemClick(item)">查看详情</span>
              <span class="time">{{ item.startTime }}</span>
            </div>
            <!-- 接收方 -->
            <div class="record-col right">
              <div class="flex flex-col min-w-0 items-end">
                <span class="name">{{ item.receiverName }}</span>
                <span class="role">接收方</span>
              </div>
              <img :src="item.receiverAvatar || '/src/assets/avatar.png'" class="avatar" />
            </div>
          </div>
        </div>
        <div v-else class="text-center text-slate-400 py-8">暂无文字答疑记录</div>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>

  <!-- 全局聊天面板 -->
  <el-dialog
    v-model="showGlobalChat"
    title="答疑记录"
    width="520px"
    :close-on-click-modal="false"
    destroy-on-close
    class="global-chat-dialog"
    @close="showGlobalChat = false">
    <div class="chat-container">
      <div class="chat-main">
        <!-- 消息列表 -->
        <div ref="messageListRef" class="message-list">
          <div
            v-for="(message, index) in globalChatMessages"
            :key="message.id"
            class="message-item"
            :class="{ self: message.isSelf }">
            <div class="message-content">
              <div class="message-header">
                <span class="sender-name">{{ message.senderName }}</span>
                <span class="message-time">{{ message.sendTime }}</span>
              </div>
              <!-- 文本消息 -->
              <div v-if="message.messageType === 0" class="message-text">
                {{ message.content }}
              </div>
              <!-- 图片消息 -->
              <div v-else-if="message.messageType === 1" class="message-media">
                <el-image
                  :src="message.content"
                  :preview-src-list="[message.content]"
                  fit="cover"
                  class="message-image">
                  <template #error>
                    <div class="image-error">
                      <el-icon><Picture /></el-icon>
                      <span>加载失败</span>
                    </div>
                  </template>
                </el-image>
              </div>
              <!-- 音视频消息 -->
              <div v-else-if="message.msgType === 2" class="message-media">
                <video v-if="isVideoFile(message.content)" controls class="message-video">
                  <source :src="message.content" type="video/mp4" />
                  您的浏览器不支持视频播放
                </video>
                <audio v-else controls class="message-audio">
                  <source :src="message.content" type="audio/mpeg" />
                  您的浏览器不支持音频播放
                </audio>
              </div>
              <!-- 其他文件消息 -->
              <div v-else-if="message.msgType === 3" class="message-file" @click="handleFileDownload(message.content)">
                <el-icon><Document /></el-icon>
                <span class="file-name">{{ getFileName(message.content) }}</span>
                <el-icon><Download /></el-icon>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>
<script setup>
import { computed, ref, watch, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { postQuestionLlike, postCloseQuestion, deleteQuestion } from '@/axios/api/question'
import { ElMessage, ElMessageBox } from 'element-plus'
import QuestionDialog from '@/views/Submit/components/QuestionDialog.vue'
import { getUserInfo } from '@/utils/webStorage'
import { MoreFilled } from '@element-plus/icons-vue'
import ReportDialog from '@/components/commonUI/ReportDialog.vue'
import VoiceCallDialog from '@/components/VoiceCallDialog.vue'
import { useChatStore } from '@/stores/chatStore'
import wsClient, { MessageType } from '@/utils/websocket'
import { useRoute, useRouter } from 'vue-router'
import { formatTime } from '@/utils/transIUtils'
import { get } from '@/axios/utils/request'
import { Phone, VideoCamera, Message, Back } from '@element-plus/icons-vue'
import jd from '@/assets/jd.png'


const route = useRoute()
const router = useRouter()
const tab = route.query.tab
console.log(tab)

const props = defineProps({
  question: {
    type: Object,
    required: true,
  },
  // 是否显示答疑相关按钮
  showInviteButtons: {
    type: Boolean,
    default: false,
  },
  // 选中的专家
  selectedExpert: {
    type: Object,
    default: null,
  },
})
// 举报相关
const showReportDialog = ref(false)
const reportInfo = computed(() => ({
  type: 'question',
  id: props.question?.id,
  title: props.question?.title,
  content: props.question?.content,
}))

const emit = defineEmits(['toggleFollow', 'scrollToAnswerInput', 'showInviteDialog', 'showShare', 'refresh'])

// 使用响应式引用来跟踪关注状态
const localIsLiked = ref(props.question?.isLiked || false)

// 使用计算属性来获取关注状态
const isFollowed = computed(() => localIsLiked.value)

// 判断是否是问题作者
const isQuestionAuthor = computed(() => {
  const userInfo = getUserInfo()
  return userInfo.uid === props.question?.uid
})

const tagTypes = [
  'primary', // 蓝色
  'success', // 绿色
  'warning', // 橙色
  'danger', // 红色
  'info', // 紫色
  'primary', // 蓝色
  'success', // 绿色
  'warning', // 橙色
  'danger', // 红色
  'info', // 紫色
]

// 问题状态映射
const statusMap = {
  0: {
    text: '进行中',
    type: 'success',
  },
  1: {
    text: '已关闭',
    type: 'info',
  },
  2: {
    text: '已删除',
    type: 'danger',
  },
  3: {
    text: '待审核',
    type: 'warning',
  },
}

// 获取状态文本
const getStatusText = computed(() => {
  return statusMap[props.question?.status || 0]?.text || '未知状态'
})

// 获取状态标签类型
const getStatusTagType = computed(() => {
  return statusMap[props.question?.status || 0]?.type || 'info'
})

const showEditDialog = ref(false)
const showCloseDialog = ref(false)
const closeReason = ref('')

// 聊天相关
const chatStore = useChatStore()
const currentUser = computed(() => chatStore.loginUserInfo)

// 会议相关
const meetingRoom = ref('')

// 语音通话相关
const showVoiceCall = ref(false)
const voiceCallData = ref({})
const voiceCallBaseUrl = ref(window.config_global.MEETING_BASE_URL || 'http://localhost:3000')

// 答疑记录弹窗相关
const showRecordDialog = ref(false)
const recordTab = ref('call') // 'call' | 'chat'
const callRecordList = ref([])
const chatRecordList = ref([])

// 点击答疑记录按钮
async function showQARecords() {
  try {
    const res = await get('question/answer/record', { id: props.question.id })
    if (res.code === 0 && res.data) {
      callRecordList.value = res.data.callRecordList || []
      chatRecordList.value = res.data.chatRecordList || []
      showRecordDialog.value = true
      recordTab.value = 'call'
      await nextTick()
    } else {
      callRecordList.value = []
      chatRecordList.value = []
      showRecordDialog.value = true
      recordTab.value = 'call'
    }
  } catch (e) {
    callRecordList.value = []
    chatRecordList.value = []
    showRecordDialog.value = true
    recordTab.value = 'call'
  }
}

const messageListRef = ref(null)
const showGlobalChat = ref(false)
const globalChatMessages = ref([])

// 点击跳转到问题详情
async function handleItemClick(item) {
  // 请求聊天记录
  try {
    const res = await get('question/chatmessages', { sessionId: item.id })
    if (res.code === 0 && Array.isArray(res.data)) {
      let data = res.data || []
      let senderId = ''
      data.forEach((item) => {
        // item.senderId = item.senderId || item.sender
        if (!senderId) {
          senderId = item.senderId
          item.isSelf = true
        } else {
          if (item.senderId === senderId) {
            item.isSelf = true
          } else {
            item.isSelf = false
          }
        }
      })
      globalChatMessages.value = data
    } else {
      globalChatMessages.value = []
    }
  } catch (e) {
    globalChatMessages.value = []
  }
  showGlobalChat.value = true
  nextTick(() => {
    scrollToBottom()
  })
}
// 滚动到底部
const scrollToBottom = () => {
  if (messageListRef.value) {
    messageListRef.value.scrollTop = messageListRef.value.scrollHeight
  }
}

// 判断是否是视频文件
const isVideoFile = (url) => {
  const videoExtensions = ['.mp4', '.webm', '.ogg']
  return videoExtensions.some((ext) => url.toLowerCase().endsWith(ext))
}

// 从URL中获取文件名
const getFileName = (url) => {
  try {
    const urlObj = new URL(url)
    const pathname = urlObj.pathname
    return pathname.substring(pathname.lastIndexOf('/') + 1)
  } catch (error) {
    return url.substring(url.lastIndexOf('/') + 1)
  }
}
// 处理文件下载
const handleFileDownload = (url) => {
  try {
    // 创建一个隐藏的a标签
    const link = document.createElement('a')
    link.href = url
    link.download = getFileName(url) // 设置下载文件名
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error) {
    console.error('下载文件失败:', error)
    ElMessage.error('下载文件失败')
  }
}
// 使用props中的selectedExpert
const selectedExpert = computed(() => props.selectedExpert)

async function handleToggleFollow() {
  try {
    await postQuestionLlike({ questionId: props.question.id + '' })
    localIsLiked.value = !localIsLiked.value // 切换本地状态
    // 通知父组件刷新数据
    emit('refresh')
    ElMessage.success(isFollowed.value ? '关注成功' : '已取消关注')
  } catch (error) {
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 编辑成功后的处理
const handleEditSuccess = () => {
  showEditDialog.value = false
  // 通知父组件刷新数据
  emit('refresh')
}

// 处理删除问题
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm('确定要删除这个问题吗？删除后将无法恢复。', '删除确认', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await deleteQuestion(props.question.id)
    ElMessage.success('删除成功')
    // 通知父组件刷新数据
    // emit('refresh')
    router.back()
  } catch (error) {
    console.log(error);

    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + error)
    }
  }
}

// 确认关闭问题
const confirmClose = async () => {
  if (!closeReason.value.trim()) {
    ElMessage.warning('请输入关闭原因')
    return
  }

  try {
    await postCloseQuestion({
      closeReason: closeReason.value.trim(),
      id: props.question.id,
    })
    ElMessage.success('问题已关闭')
    showCloseDialog.value = false
    closeReason.value = ''
    // 通知父组件刷新数据
    emit('refresh')
  } catch (error) {
    console.log(error);
    ElMessage.error('关闭失败：' + error)
  }
}

// 监听关闭弹框，重置表单
watch(
  () => showCloseDialog.value,
  (newVal) => {
    if (!newVal) {
      closeReason.value = ''
    }
  },
)

// 处理举报成功
const handleReportSuccess = () => {
  ElMessage.success('举报已提交，我们会尽快处理')
}

// WebSocket事件处理
onMounted(() => {
  // 注册WebSocket事件处理器
  wsClient.on(MessageType.CHAT, handleChatMessage)
  // 聊天相关消息已移至全局App.vue处理
  wsClient.on(MessageType.MEETING_INVITE, handleMeetingInvite)
  wsClient.on(MessageType.MEETING_ACCEPT, handleMeetingAccept)
  wsClient.on(MessageType.MEETING_END, handleMeetingEndMessage)
})

onBeforeUnmount(() => {
  // 移除WebSocket事件处理器
  wsClient.off(MessageType.CHAT, handleChatMessage)
  // 聊天相关消息已移至全局App.vue处理
  wsClient.off(MessageType.MEETING_INVITE, handleMeetingInvite)
  wsClient.off(MessageType.MEETING_ACCEPT, handleMeetingAccept)
  wsClient.off(MessageType.MEETING_END, handleMeetingEndMessage)
})

// 语音通话发起状态
const isStartingVoiceCall = ref(false)

// 检查网络连接状态
const checkNetworkStatus = () => {
  if (!navigator.onLine) {
    console.error('网络断开')
    ElMessage.error('网络连接已断开，请检查网络设置')
    return false
  }
  return true
}

// 开始音频会议
async function startAudioMeeting() {
  // 防止频繁点击
  if (isStartingVoiceCall.value) {
    console.log('正在发起语音通话，请勿重复点击')
    return
  }

  try {
    isStartingVoiceCall.value = true

    console.log('=== 开始发起语音通话 ===')
    console.log('点击时间:', new Date().toISOString())

    // 检查网络连接
    if (!checkNetworkStatus()) {
      isStartingVoiceCall.value = false
      return
    }

    // 检查WebSocket连接状态
    const wsStatus = wsClient.getStatus()
    console.log('WebSocket状态:', wsStatus)

    if (!wsStatus.connected) {
      ElMessage.error('网络连接失败，请刷新页面重试')
      isStartingVoiceCall.value = false
      return
      // console.error('WebSocket未连接，尝试重新连接...')
      // ElMessage.error('网络连接断开，正在重新连接...')

      // 尝试重新连接
      // try {
      //   await wsClient.initConnect(true)
      //   const newStatus = wsClient.getStatus()
      //   console.log('重连后状态:', newStatus)

      //   if (!newStatus.connected) {
      //     ElMessage.error('网络连接失败，请检查网络后刷新页面重试')
      //     isStartingVoiceCall.value = false
      //     return
      //   }

      //   ElMessage.success('网络连接已恢复')
      // } catch (reconnectError) {
      //   console.error('WebSocket重连失败:', reconnectError)
      //   ElMessage.error('网络重连失败，请刷新页面重试')
      //   isStartingVoiceCall.value = false
      //   return
      // }
    }

    // 获取当前用户信息并验证
    const userInfo = getUserInfo()
    console.log('当前用户信息:', userInfo)

    if (!userInfo || !userInfo.uid || !userInfo.username) {
      console.error('用户信息不完整:', userInfo)
      ElMessage.error('用户信息无效，请重新登录')
      isStartingVoiceCall.value = false
      return
    }

    // 验证问题信息
    if (!props.question || !props.question.uid || !props.question.id) {
      console.error('问题信息不完整:', props.question)
      ElMessage.error('问题信息错误，请刷新页面重试')
      isStartingVoiceCall.value = false
      return
    }

    // 发送在线状态检查（语音通话）
    const isOnline = await wsClient.checkOnlineStatus(userInfo.uid, props.question.uid)
    if (!isOnline) {
      ElMessage.warning('对方不在线，暂无法发起语音通话')
      isStartingVoiceCall.value = false
      return
    }

    // 构建通话数据
    const callData = {
      senderId: userInfo.uid,
      receiverId: props.question.uid,
      senderName: userInfo.username,
      receiverName: props.question.username || '专家',
      questionId: props.question.id,
      startTime: Date.now(),
    }

    console.log('语音通话数据:', callData)

    // 构建WebSocket消息
    const wsMessage = {
      senderId: userInfo.uid,
      receiverId: props.question.uid,
      senderName: userInfo.username,
      questionId: props.question.id,
    }

    console.log('发送WebSocket消息:', wsMessage)

    // 通过WebSocket发送语音通话请求
    const sendResult = wsClient.send(MessageType.VOICE_CALL, wsMessage)

    if (!sendResult) {
      console.error('WebSocket发送失败')
      ElMessage.error('发送通话请求失败，请检查网络连接')
      isStartingVoiceCall.value = false
      return
    }

    console.log('✅ WebSocket消息发送成功')

    // 设置语音通话数据并打开弹窗
    voiceCallData.value = callData
    showVoiceCall.value = true

    console.log('✅ 语音通话弹窗已打开')
    console.log('=== 语音通话发起流程完成 ===')

    // 成功后立即重置状态
    isStartingVoiceCall.value = false
  } catch (error) {
    console.error('❌ 发起语音通话失败:', error)
    ElMessage.error('发起语音通话失败: ' + (error || '未知错误'))
    isStartingVoiceCall.value = false
  }
}

// 开始视频会议
async function startVideoMeeting() {
  // 防止频繁点击
  if (isStartingVoiceCall.value) {
    console.log('正在发起视频通话，请勿重复点击')
    return
  }

  try {
    // isStartingVoiceCall.value = true

    console.log('=== 开始发起视频通话 ===')
    console.log('点击时间:', new Date().toISOString())

    // 检查网络连接
    if (!checkNetworkStatus()) {
      isStartingVoiceCall.value = false
      return
    }

    const newStatus = wsClient.getStatus()
    console.log('重连后状态:', newStatus)

    if (!newStatus.connected) {
      ElMessage.error('网络连接失败，请刷新页面重试')
      isStartingVoiceCall.value = false
      return
    }

    // 获取当前用户信息并验证
    const userInfo = getUserInfo()
    console.log('当前用户信息:', userInfo)

     // 发送在线状态检查（语音通话）
    const isOnline = await wsClient.checkOnlineStatus(userInfo.uid, props.question.uid)
    if (!isOnline) {
      ElMessage.warning('对方不在线，暂无法发起视频通话')
      isStartingVoiceCall.value = false
      return
    }

    if (!userInfo || !userInfo.uid || !userInfo.username) {
      console.error('用户信息不完整:', userInfo)
      ElMessage.error('用户信息无效，请重新登录')
      isStartingVoiceCall.value = false
      return
    }

    // 验证问题信息
    if (!props.question || !props.question.uid || !props.question.id) {
      console.error('问题信息不完整:', props.question)
      ElMessage.error('问题信息错误，请刷新页面重试')
      isStartingVoiceCall.value = false
      return
    }

    // 构建通话数据
    const callData = {
      senderId: userInfo.uid,
      receiverId: props.question.uid,
      senderName: userInfo.username,
      receiverName: props.question.username || '专家',
      questionId: props.question.id,
      startTime: Date.now(),
      isVideo: true, // 标记为视频通话
    }

    console.log('视频通话数据:', callData)

    // 构建WebSocket消息
    const wsMessage = {
      senderId: userInfo.uid,
      receiverId: props.question.uid,
      senderName: userInfo.username,
      questionId: props.question.id,
      isVideo: true, // 标记为视频通话
    }

    console.log('发送WebSocket消息:', wsMessage)

    // 通过WebSocket发送视频通话请求
    const sendResult = wsClient.send(MessageType.VIDEO_CALL, wsMessage)

    if (!sendResult) {
      console.error('WebSocket发送失败')
      ElMessage.error('发送通话请求失败，请检查网络连接')
      isStartingVoiceCall.value = false
      return
    }

    console.log('✅ WebSocket消息发送成功')

    // 设置视频通话数据并打开弹窗
    voiceCallData.value = callData
    showVoiceCall.value = true

    console.log('✅ 视频通话弹窗已打开')
    console.log('=== 视频通话发起流程完成 ===')

    // 成功后立即重置状态
    isStartingVoiceCall.value = false
  } catch (error) {
    console.error('❌ 发起视频通话失败:', error)
    ElMessage.error('发起视频通话失败: ' + (error || '未知错误'))
    isStartingVoiceCall.value = false
  }
}

// 开始文字聊天
// 点击按钮后，发送 socket 格式
// {"type":"gen-session","data":{"senderId":111,"receiverId":222,"questionId":999}
// 然后发起方和接收方都会接收到socket 消息，格式如下
// {"type":"session-id","data":{"sessionId":"888"}
// 使用这个sessionId，参与后面的消息对接
// 双方呼起聊天框，可以向对方发送消息。消息格式如下。
// {"type":"chat-message","data":{"senderId":111,"receiverId":222,"senderName":"蒋XX","sessionId":"888","questionId":999,"content":"xxxxxxxxxxxxxxxxxxxx","msgType":消息类型 0文本 1图片 2音视频 3其他文件}}
// 可以先实现发送文本消息，其他消息后续在实现

async function startTextChat() {
  try {


    // 检查网络连接
    if (!checkNetworkStatus()) {
      isStartingVoiceCall.value = false
      return
    }

    const newStatus = wsClient.getStatus()
    console.log('重连后状态:', newStatus)

    if (!newStatus.connected) {
      ElMessage.error('网络连接失败，请刷新页面重试')
      isStartingVoiceCall.value = false
      return
    }

    // 获取当前用户信息并验证
    const userInfo = getUserInfo()
    console.log('当前用户信息:', userInfo)

    if (!userInfo || !userInfo.uid || !userInfo.username) {
      console.error('用户信息不完整:', userInfo)
      ElMessage.error('用户信息无效，请重新登录')
      return
    }

    // 在线状态检查
    const isOnline = await wsClient.checkOnlineStatus(userInfo.uid, props.question.uid)
    if (!isOnline) {
      ElMessage.warning('对方不在线，暂无法发起文字聊天')
      return
    }

    // 验证问题信息
    if (!props.question || !props.question.uid || !props.question.id) {
      console.error('问题信息不完整:', props.question)
      ElMessage.error('问题信息错误，请刷新页面重试')
      return
    }

    // 发送gen-session请求
    const genSessionData = {
      senderId: userInfo.uid,
      receiverId: props.question.uid,
      questionId: props.question.id,
    }

    console.log('发送gen-session消息:', genSessionData)

    // 通过WebSocket发送生成会话请求
    const sendResult = wsClient.send(MessageType.GEN_SESSION, genSessionData)

    if (!sendResult) {
      console.error('WebSocket发送失败')
      ElMessage.error('发送聊天请求失败，请检查网络连接')
      return
    }

    console.log('✅ 聊天会话请求发送成功')
    ElMessage.success('正在建立聊天会话...')
  } catch (error) {
    console.error('❌ 发起文字聊天失败:', error)
    ElMessage.error('发起文字聊天失败: ' + (error || '未知错误'))
  }
}

// 聊天相关函数已移至全局App.vue处理
// 保持接口兼容性的空函数
function sendChatMessage(content, msgType = 0) {
  console.log('聊天功能已移至全局处理，此函数仅保持兼容性')
  return true
}

// 处理发送消息（保持原有的兼容性）
async function handleSendMessage(message) {
  try {
    // 聊天功能已移至全局App.vue处理
    console.log('聊天功能已移至全局处理')

    // 保留原有的非聊天逻辑（注释掉，因为chatApi已移除）
    // 如果是图片或文件消息，先上传
    // if (message.type === 'image') {
    //   const formData = new FormData()
    //   formData.append('file', message.file)
    //   const { data } = await chatApi.uploadChatImage(formData)
    //   message.content = data.url
    // } else if (message.type === 'file') {
    //   const formData = new FormData()
    //   formData.append('file', message.file)
    //   const { data } = await chatApi.uploadChatFile(formData)
    //   message.content = data.url
    // }

    // 通过WebSocket发送消息（保留原有逻辑）
    wsClient.send(MessageType.CHAT, {
      ...message,
      to: selectedExpert.value.id,
    })
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败')
  }
}

// WebSocket消息处理函数（已移至全局App.vue处理）
function handleChatMessage(message) {
  console.log('聊天消息处理已移至全局App.vue')
  // 保留原有的非聊天逻辑可以在这里处理
}

function handleMeetingInvite(data) {
  ElMessage.info(`收到来自 ${data.expert.name} 的${data.type === 'audio' ? '音频' : '视频'}会议邀请`)
}

function handleMeetingAccept(data) {
  ElMessage.success(`${data.expert.name} 已接受会议邀请`)
}

function handleMeetingEndMessage(data) {
  if (data.roomName === meetingRoom.value) {
    showMeeting.value = false
    meetingRoom.value = ''
    ElMessage.info('会议已结束')
  }
}

// 显示答疑记录
// function showQARecords() {
//   ElMessage.info('答疑记录功能开发中...')
//   // TODO: 实现答疑记录查看功能
// }

// 处理语音通话结束
function handleVoiceCallEnd(callEndData) {
  try {
    console.log('语音通话结束:', callEndData)
  } catch (error) {
    console.error('处理语音通话结束失败:', error)
  }
}
</script>
<style scoped>
.my-invite-panel.question-detail-header {
  border-radius: 14px;
  background: linear-gradient(135deg, #fafdff 0%, #e3f0ff 100%);
  border: none;
  box-shadow: 0 2px 10px 0 rgba(56, 112, 255, 0.07);
  padding: 0 18px 10px 18px;
  margin: 0 0 20px 0;
}
.panel-title {
  font-size: 17px;
  font-weight: 600;
  color: #1a237e;
}
.main-title {
  color: #1a237e;
}
.desc {
  color: #4b5563;
}

.status-tag {
  font-weight: 500;
  letter-spacing: 0.5px;
}

/* 不同状态的标签样式 */
:deep(.el-tag.el-tag--success) {
  background-color: #67c23a;
  border-color: #67c23a;
}

:deep(.el-tag.el-tag--info) {
  background-color: #909399;
  border-color: #909399;
}

:deep(.el-tag.el-tag--danger) {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

:deep(.el-tag.el-tag--warning) {
  background-color: #e6a23c;
  border-color: #e6a23c;
}

.ml-auto {
  margin-left: auto;
}

.close-form {
  padding: 20px 0;
}

.form-item {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.form-label.required::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 按钮样式优化 */
:deep(.el-button--warning) {
  background: #e6a23c;
  border-color: #e6a23c;
  color: #fff;
}

:deep(.el-button--warning:hover) {
  background: #cf9236;
  border-color: #cf9236;
}

:deep(.el-button--danger) {
  background: #f56c6c;
  border-color: #f56c6c;
  color: #fff;
}

:deep(.el-button--danger:hover) {
  background: #e45656;
  border-color: #e45656;
}

.mr-1 {
  margin-right: 4px;
}

.tag-modern {
  font-weight: 500;
  color: #333;
  border: 1px solid #e4e7ed;
  background: #f8f9fa;
  transition: all 0.3s ease;
}

.tag-modern:hover {
  background: #e9ecef;
  border-color: #dee2e6;
}

/* 不同标签类型的颜色 */
:deep(.el-tag.el-tag--primary) {
  background: #e3f2fd;
  border-color: #2196f3;
  color: #1976d2;
}

:deep(.el-tag.el-tag--success) {
  background: #e8f5e8;
  border-color: #4caf50;
  color: #2e7d32;
}

:deep(.el-tag.el-tag--warning) {
  background: #fff3e0;
  border-color: #ff9800;
  color: #f57c00;
}

:deep(.el-tag.el-tag--danger) {
  background: #ffebee;
  border-color: #f44336;
  color: #d32f2f;
}

:deep(.el-tag.el-tag--info) {
  background: #f3e5f5;
  border-color: #9c27b0;
  color: #7b1fa2;
}

/* 添加更多颜色变体 */
:deep(.el-tag.el-tag--primary:nth-child(6n + 1)) {
  background: #e1f5fe;
  border-color: #03a9f4;
  color: #0277bd;
}

:deep(.el-tag.el-tag--success:nth-child(6n + 2)) {
  background: #f1f8e9;
  border-color: #8bc34a;
  color: #558b2f;
}

:deep(.el-tag.el-tag--warning:nth-child(6n + 3)) {
  background: #fff8e1;
  border-color: #ffc107;
  color: #f57f17;
}

:deep(.el-tag.el-tag--danger:nth-child(6n + 4)) {
  background: #ffcdd2;
  border-color: #e91e63;
  color: #c2185b;
}

:deep(.el-tag.el-tag--info:nth-child(6n + 5)) {
  background: #fce4ec;
  border-color: #e91e63;
  color: #c2185b;
}

.ml-2 {
  margin-left: 8px;
}
.action-btn {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  height: 32px;
  padding: 0 8px;
  border-radius: 16px;
  background: none;
  color: #4b5563;
  font-size: 15px;
  cursor: pointer;
  transition: background 0.18s, color 0.18s;
  border: none;
  box-shadow: none;
}

.chat-dialog-content {
  height: 600px;
}

:deep(.el-dialog__body) {
  padding: 0;
  height: 600px;
}

/* 经典答疑标志样式 */
.classic-qa-badge {
  position: relative;
  background: linear-gradient(135deg, #ffd700 0%, #ffed4e 50%, #ffd700 100%);
  border-radius: 20px;
  padding: 8px 16px;
  box-shadow: 0 4px 15px rgba(255, 215, 0, 0.3), 0 0 0 2px rgba(255, 215, 0, 0.2),
    inset 0 1px 0 rgba(255, 255, 255, 0.4);
  transform: translateY(0);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
  cursor: pointer;
}

.classic-qa-badge:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(255, 215, 0, 0.4), 0 0 0 3px rgba(255, 215, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.6);
}

.badge-content {
  display: flex;
  align-items: center;
  gap: 8px;
  position: relative;
  z-index: 2;
}

.badge-icon {
  font-size: 20px;
  animation: trophy-glow 2s ease-in-out infinite alternate;
}

.badge-text {
  display: flex;
  flex-direction: column;
  line-height: 1;
}

.badge-title {
  font-size: 14px;
  font-weight: 700;
  color: #8b4513;
  text-shadow: 0 1px 2px rgba(255, 255, 255, 0.8);
  letter-spacing: 0.5px;
}

.badge-subtitle {
  font-size: 10px;
  font-weight: 500;
  color: #a0522d;
  text-shadow: 0 1px 1px rgba(255, 255, 255, 0.6);
  margin-top: 1px;
}

.badge-shine {
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: linear-gradient(45deg, transparent 30%, rgba(255, 255, 255, 0.3) 50%, transparent 70%);
  animation: shine 3s ease-in-out infinite;
  pointer-events: none;
}

@keyframes trophy-glow {
  0% {
    filter: drop-shadow(0 0 2px rgba(255, 215, 0, 0.5));
  }
  100% {
    filter: drop-shadow(0 0 8px rgba(255, 215, 0, 0.8));
  }
}

@keyframes shine {
  0% {
    transform: translateX(-100%) translateY(-100%) rotate(45deg);
  }
  50% {
    transform: translateX(100%) translateY(100%) rotate(45deg);
  }
  100% {
    transform: translateX(-100%) translateY(-100%) rotate(45deg);
  }
}

/* 添加脉冲效果 */
.classic-qa-badge::before {
  content: '';
  position: absolute;
  top: -2px;
  left: -2px;
  right: -2px;
  bottom: -2px;
  background: linear-gradient(45deg, #ffd700, #ffed4e, #ffd700, #ffed4e);
  border-radius: 22px;
  z-index: -1;
  animation: pulse-border 2s ease-in-out infinite;
  opacity: 0.6;
}

@keyframes pulse-border {
  0%,
  100% {
    opacity: 0.6;
    transform: scale(1);
  }
  50% {
    opacity: 0.8;
    transform: scale(1.02);
  }
}

/* 答疑记录弹窗三栏布局优化 */
.record-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 1rem;
  background: #f8fafc;
  border-radius: 1rem;
  padding: 1.2rem 1.5rem;
}
.record-col {
  display: flex;
  align-items: center;
  min-width: 0;
}
.record-col.left,
.record-col.right {
  flex: 0 0 180px;
  max-width: 180px;
  min-width: 120px;
}
.record-col.right {
  justify-content: end;
}
.record-col.center {
  flex: 0 0 120px;
  max-width: 120px;
  min-width: 80px;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
}
.record-col .name {
  font-weight: 500;
  color: #1a237e;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 110px;
}
.record-col .role {
  font-size: 12px;
  color: #64748b;
}
.record-col .avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #bfdbfe;
  margin-right: 10px;
}
.record-col.right .avatar {
  margin-left: 10px;
  margin-right: 0;
}
.record-col.center .icon {
  font-size: 22px;
  margin-bottom: 2px;
}
.record-col.center .time {
  font-size: 12px;
  color: #64748b;
}
</style>
